package com.qf.servlet;

import com.qf.entity.Admin;
import com.qf.util.DataUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

/**
 * 随便加的一行注释
 * 111111111111111111111111111 张三的内容
 *1231231312132131
 *
 *
 * description: 登录处理的Servlet
 * author: Ken
 * 公众号：Java架构栈
 *
 * 22222222222222222222222222222 李四的内容
 */
@WebServlet(urlPatterns = "/login", loadOnStartup = 5)
public class LoginServlet extends HttpServlet {

    /**
     * 处理登录逻辑
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("登录的Servlet触发！当前线程名称：" + Thread.currentThread().getName() + " 当前对象：" + this.hashCode());

        //接收登录的信息
        String username = req.getParameter("un");
        String password = req.getParameter("pw");
        //验证码
        String inputCode = req.getParameter("code");

        //从session中获取生成的验证码
        HttpSession session = req.getSession();
        String code = (String) session.getAttribute("code");
        //验证码的创建时间
        long createTime = (long) session.getAttribute("code_create_time");

        if (System.currentTimeMillis() - createTime > 60 * 1000) {
            //验证码过期
            resp.sendRedirect("login.jsp?status=3");
            return;
        }

        //inputCode -> 用户输入的验证码？？  inputCode 对比 CodeServlet.code
        if (inputCode == null || !inputCode.equals(code)) {
            //验证码不正确
            resp.sendRedirect("login.jsp?status=2");
            return;
        }

        //验证码对比通过，验证码也需要移除掉
        session.removeAttribute("code");
        session.removeAttribute("code_create_time");

        //参数的校验

        //进行登录的判断
        Admin admin = DataUtils.queryAdmin(username, password);

        if (admin != null) {
            //保存登录信息
            req.getSession().setAttribute("login_user", admin);
            //跳转到主页
            resp.sendRedirect("index.jsp");
        } else {
            //跳转回登录页
            resp.sendRedirect("login.jsp?status=1");
        }
    }
}
